/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package login;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 *
 * @author odeen
 */
@ManagedBean(name = "login")
@ApplicationScoped
public class Login {

    @ManagedProperty(value = "#{authenticationManager}") //Está definida con un alias en controladorSpring-seguridad.xml
    private AuthenticationManager am;
    private String j_username;
    private String j_password;

    public String logarse() {
        try {
            SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
            Authentication request = new UsernamePasswordAuthenticationToken(j_username, j_password);
            Authentication result = am.authenticate(request);
            if (result.isAuthenticated()) {
                SecurityContextHolder.getContext().setAuthentication(result);
            } else {
                FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "El usuario o el password ingresado son invalidos.", null);
                FacesContext.getCurrentInstance().addMessage("loginForm", facesMsg);
                return "login.xhtml";
            }
        } catch (AuthenticationException e) {
            FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "El usuario o el password ingresado son invalidos.", null);
            FacesContext.getCurrentInstance().addMessage("loginForm", facesMsg);
            return "login.xhtml";
        }
        return "admin/index.xhtml";
    }

    public String salir() throws ServletException {
        ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).logout();
        SecurityContextHolder.getContext().setAuthentication(null);
        return "/index.xhtml";
    }

    /**
     * Creates a new instance of Logica
     */
    public Login() {
    }

    public AuthenticationManager getAm() {
        return am;
    }

    public void setAm(AuthenticationManager am) {
        this.am = am;
    }

    public String getJ_password() {
        return j_password;
    }

    public void setJ_password(String j_password) {
        this.j_password = j_password;
    }

    public String getJ_username() {
        return j_username;
    }

    public void setJ_username(String j_username) {
        this.j_username = j_username;
    }
}
